'use client';

import dynamic from 'next/dynamic';
import React, { useState, useEffect, Suspense, useRef } from 'react';
import Link from 'next/link';
import { useRouter, usePathname } from 'next/navigation';
import { Layout as AntLayout, Menu, Button, Avatar, Dropdown, Breadcrumb, Card, message, ConfigProvider, theme, Spin } from 'antd';
import {
  MenuUnfoldOutlined,
  MenuFoldOutlined,
  HomeOutlined,
  ClockCircleOutlined,
  CalendarOutlined,
  UserOutlined,
  TeamOutlined,
  FolderOutlined,
  BellOutlined,
  UserSwitchOutlined,
  KeyOutlined,
  BuildOutlined,
  CheckSquareOutlined,
  SettingOutlined,
  RightOutlined,
  SolutionOutlined,
  FileSearchOutlined,
  UserAddOutlined,
  ScheduleOutlined,
  PieChartOutlined,
  FileTextOutlined,
  ReadOutlined
} from '@ant-design/icons';
import { getUserInfo } from '@/lib/user';
import Cookies from 'js-cookie';
import { css } from '@emotion/css';
import { useAuth } from '@/hooks/useAuth';
import Loading from '@/app/loading';
import { LoadingLayout } from './LoadingLayout';
import { 
  Box,
  Popper,
  Grow,
  Paper,
  ClickAwayListener,
  MenuList,
  MenuItem,
  ListItemIcon,
  ListItemText,
  Divider,
  Typography
} from '@mui/material';
import {
  Person as PersonIcon,
  Settings as SettingsIcon,
  ExitToApp as LogoutIcon,
  Lock as LockIcon
} from '@mui/icons-material';

const { Header, Sider, Content } = AntLayout;

const menuStyles = css`
  .ant-menu-item, .ant-menu-submenu-title {
    transition: all 0.3s ease;
    &:hover {
      background-color: #1890ff;
      color: #fff;
    }
  }
  .ant-menu-item-selected {
    background-color: #1890ff !important;
    &::after {
      border-right: 3px solid #fff;
    }
  }

  /* 自定义滚动条样式 */
  &.scrollable-menu {
    max-height: calc(100vh - 64px);
    overflow-y: auto;
    overflow-x: hidden;

    /* 滚动条样式 */
    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-track {
      background: #001529;
    }

    &::-webkit-scrollbar-thumb {
      background: #1890ff;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-thumb:hover {
      background: #40a9ff;
    }
  }
`;

const buttonStyles = css`
  &:hover {
    background-color: rgba(255, 255, 255, 0.1);
  }
`;

const contentStyles = css`
  .site-layout-background {
    background: transparent;
    margin: 0;
    padding: 0;
  }
  .content-wrapper {
    background: transparent;
    margin: 0;
    padding: 0;
    box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  }
  .breadcrumb-container {
    padding: 18px 24px;
    background: #fff;
    margin: 0;
    border-bottom: 2px solid #e8e8e8;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    position: relative;
    z-index: 1;
  }
  .content-card {
    background: linear-gradient(to right, #e6f7ff, #bae7ff);
    border: none;
    border-radius: 0;
    margin: 0;
    padding: 24px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    position: relative;
    z-index: 0;
  }
`;

const breadcrumbStyles = css`
  .ant-breadcrumb {
    display: flex;
    align-items: center;
  }
  .ant-breadcrumb-link {
    color: #1890ff;
    text-decoration: none;
    &:last-child {
      color: #003a8c;
      font-weight: bold;
    }
  }
  .breadcrumb-separator {
    margin: 0 8px;
    color: #1890ff;
  }
`;

// 创建一个新的客户端内容组件
const ContentArea: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [isLoading, setIsLoading] = useState(true);
  const pathname = usePathname();

  // 处理面包屑导航
  const getBreadcrumbItems = () => {
    const paths = pathname.split('/').filter(Boolean);
    const items = [
      {
        title: '首页',
        href: '/dashboard'
      }
    ];

    let currentPath = '';
    paths.forEach(path => {
      currentPath += `/${path}`;
      items.push({
        title: path.charAt(0).toUpperCase() + path.slice(1).replace(/-/g, ' '),
        href: currentPath
      });
    });

    return items;
  };

  useEffect(() => {
    const timer = setTimeout(() => {
      setIsLoading(false);
    }, 500);

    return () => clearTimeout(timer);
  }, [children]); // 当 children 变化时重新触发加载效果

  const breadcrumbItems = getBreadcrumbItems();

  return (
    <div className="content-wrapper" style={{ 
      margin: 0,
      boxShadow: '0 2px 8px rgba(0,0,0,0.15)'
    }}>
      <div className={`${breadcrumbStyles} breadcrumb-container`} style={{
        background: '#fff',
        width: '100%',
        padding: '18px 24px',
        boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
        borderBottom: '2px solid #e8e8e8',
        position: 'relative',
        zIndex: 1
      }}>
        <Breadcrumb separator={<RightOutlined className="breadcrumb-separator" />}>
          {breadcrumbItems.map((item, index) => (
            <Breadcrumb.Item key={index}>
              <Link href={item.href} className="ant-breadcrumb-link">{item.title}</Link>
            </Breadcrumb.Item>
          ))}
        </Breadcrumb>
      </div>
      <Card 
        className="content-card" 
        style={{ 
          margin: 0,
          borderRadius: 0,
          boxShadow: '0 1px 3px rgba(0,0,0,0.1)',
          background: 'linear-gradient(to right, #e6f7ff, #bae7ff)',
          position: 'relative',
          minHeight: '200px'
        }}
      >
        {isLoading ? (
          <div style={{
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            background: 'rgba(255, 255, 255, 0.5)',
            backdropFilter: 'blur(4px)',
            WebkitBackdropFilter: 'blur(4px)',
          }}>
            <Spin size="large" />
          </div>
        ) : children}
      </Card>
    </div>
  );
};

// 将 Layout 重命名为 AppLayout
const AppLayout: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [collapsed, setCollapsed] = useState(false);
  const [userInfo, setUserInfo] = useState<any>({});
  const router = useRouter();
  const pathname = usePathname();
  const { isAuthenticated, isLoading, hasPermission, userRole } = useAuth();
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const open = Boolean(anchorEl);

  useEffect(() => {
    const fetchUserInfo = async () => {
      try {
        const response = await getUserInfo();
        console.log('获取到的用户信息响应:', response);
        
        if (response?.data?.code === 1 && response?.data?.data) {
          console.log('设置用户信息:', response.data.data);
          setUserInfo(response.data.data);
        } else {
          console.error('获取用户信息失败:', response);
          message.error('获取用户信息失败');
        }
      } catch (error) {
        console.error('获取用户信息时出错：', error);
        message.error('获取用户信息失败');
      }
    };

    fetchUserInfo();
  }, []);

  // 添加调试代码
  useEffect(() => {
    console.log('当前用户角色:', userRole);
    console.log('系统首页权限:', hasPermission('dashboard'));
    console.log('考勤打卡权限:', hasPermission('attendance-management'));
    console.log('请假申请权限:', hasPermission('leave-management'));
    console.log('公告管理权限:', hasPermission('announcement-management'));
    console.log('用户管理权限:', hasPermission('user-management'));
    console.log('人事管理权限:', hasPermission('department-management') || hasPermission('academy-management') || hasPermission('attendance-management') || hasPermission('leave-management'));
    console.log('招聘管理权限:', hasPermission('recruitment-management'));
    console.log('系统设置权限:', hasPermission('system-settings'));
  }, [userRole, hasPermission]);

  if (isLoading) {
    return null;  // 不显示加载效果
  }

  if (!isAuthenticated) {
    return null;
  }

  const handleClick = (event: React.MouseEvent<HTMLElement>) => {
    event.stopPropagation();  // 阻止事件冒泡
    setAnchorEl(open ? null : event.currentTarget);  // 切换状态
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const handleLogout = () => {
    console.log('【登出操作】开始清除token');
    
    // 清除所有token存储
    Cookies.remove('token', { path: '/' });
    localStorage.removeItem('token');
    sessionStorage.removeItem('token');
    
    console.log('【登出操作】token已清除，准备重定向到登录页');
    
    // 强制刷新到登录页面，避免路由缓存问题
    window.location.replace('/login');
  };

  // 基础菜单项
  let sideMenuItems = [];

  // 先检查用户是否有基础权限
  if (hasPermission('dashboard')) {
    sideMenuItems.push({ 
      key: 'home', 
      icon: <HomeOutlined />, 
      label: '系统首页', 
      href: '/dashboard', 
      permission: 'dashboard'
    });
  }

  // 文章管理
  sideMenuItems.push({
    key: 'articleManagement',
    icon: <ReadOutlined />,
    label: '文章管理',
    href: '/article-management',
    permission: 'article-management'
  });

  if (hasPermission('attendance-management')) {
    sideMenuItems.push({ 
      key: 'clockIn', 
      icon: <ClockCircleOutlined />, 
      label: '考勤打卡', 
      href: '/attendance', 
      permission: 'attendance-management'
    });
  }

  // 考勤管理（作为独立菜单项）
  if (hasPermission('attendance-management')) {
    sideMenuItems.push({ 
      key: 'attendanceManagement', 
      icon: <CheckSquareOutlined />, 
      label: '考勤管理', 
      href: '/attendance-management', 
      permission: 'attendance-management' 
    });
  }

  // 考勤设置（作为独立菜单项）
  if (hasPermission('attendance-management')) {
    sideMenuItems.push({ 
      key: 'setCheckInTime', 
      icon: <SettingOutlined />, 
      label: '考勤设置', 
      href: '/set-check-in-time', 
      permission: 'attendance-management' 
    });
  }
  
  // 请假申请
  if (hasPermission('leave-management')) {
    sideMenuItems.push({ 
      key: 'leaveRequest', 
      icon: <CalendarOutlined />, 
      label: '请假申请', 
      href: '/leave-request', 
      permission: 'leave-management'
    });
  }

  // 假期审批（作为独立菜单项）
  if (hasPermission('leave-management')) {
    sideMenuItems.push({ 
      key: 'leaveApproval', 
      icon: <CalendarOutlined />, 
      label: '假期审批', 
      href: '/approval/leave', 
      permission: 'leave-management' 
    });
  }

  // 公告管理
  if (hasPermission('announcement-management')) {
    sideMenuItems.push({ 
      key: 'announcementManagement', 
      icon: <BellOutlined />, 
      label: '公告管理', 
      href: '/announcement-management', 
      permission: 'announcement-management'
    });
  }

  // 入职管理（作为独立菜单项）
  if (hasPermission('recruitment-management')) {
    sideMenuItems.push({
      key: 'onboardManagement',
      icon: <UserAddOutlined />,
      label: '入职管理',
      href: '/onboard',
      permission: 'recruitment-management'
    });
  }

  // 用户管理
  if (hasPermission('user-management')) {
    sideMenuItems.push({
      key: 'userManagement',
      icon: <TeamOutlined />,
      label: '用户管理',
      permission: 'user-management',
      children: [
        { key: 'adminInfo', icon: <UserSwitchOutlined />, label: '权限管理', href: '/admin-info', permission: 'role-management' },
        { key: 'empInfo', icon: <UserOutlined />, label: '员工信息', href: '/user-info', permission: 'user-management' },
        { key: 'empPwdManagement', icon: <KeyOutlined />, label: '员工密码管理', href: '/employee-password', permission: 'user-management' },
      ],
    });
  }

  // 人事管理
  const hasHRPermissions = [
    'department-management',
    'academy-management',
    'other-department-management',
    'position-management'
  ].some(permission => hasPermission(permission));

  if (hasHRPermissions) {
    sideMenuItems.push({
      key: 'hrManagement',
      icon: <FolderOutlined />,
      label: '人事管理',
      permission: 'department-management',
      children: [
        hasPermission('department-management') && { 
          key: 'departmentManagement', 
          icon: <BuildOutlined />, 
          label: '部门管理', 
          href: '/department-management', 
          permission: 'department-management' 
        },
        hasPermission('academy-management') && { 
          key: 'academyManagement', 
          icon: <BuildOutlined />, 
          label: '学院管理', 
          href: '/personnel/academy', 
          permission: 'academy-management' 
        },
        hasPermission('other-department-management') && {
          key:'otherDeptManagement',
          icon:<BuildOutlined/>,
          label:'其它部门管理',
          href:'/personnel/otherdept',
          permission:'other-department-management'
        }
      ].filter(Boolean),
    });
  }

  

  

  // 招聘管理
  if (hasPermission('recruitment-management')) {
    sideMenuItems.push({
      key: 'recruitmentManagement',
      icon: <SolutionOutlined />,
      label: '招聘管理',
      permission: 'recruitment-management',
      children: [
        { key: 'recruitmentAnnouncements', icon: <BellOutlined />, label: '招聘计划审批', href: '/recruitment/announcements', permission: 'recruitment-management' },
        { key: 'recruitmentPlan', icon: <FileSearchOutlined />, label: '招聘计划管理', href: '/recruitment/plan', permission: 'recruitment-management' },
        { key: 'candidateManagement', icon: <UserAddOutlined />, label: '应聘管理', href: '/recruitment/candidates', permission: 'recruitment-management' },
        { key: 'interviewManagement', icon: <ScheduleOutlined />, label: '面试管理', href: '/recruitment/interviews', permission: 'recruitment-management' },
        { key: 'recruitmentAnalytics', icon: <PieChartOutlined />, label: '招聘分析', href: '/recruitment/analytics', permission: 'recruitment-management' },
        { key: 'offerManagement', icon: <FileTextOutlined />, label: 'Offer管理', href: '/recruitment/offer', permission: 'recruitment-management' }
      ],
    });
  }

  // 系统设置
  if (hasPermission('system-settings')) {
    sideMenuItems.push({
      key: 'systemSettings',
      icon: <SettingOutlined />,
      label: '系统设置',
      href: '/system-settings',
      permission: 'system-settings'
    });
  }

  const generateBreadcrumbItems = () => {
    const pathSegments = pathname.split('/').filter(Boolean);
    return [
      { href: '/dashboard', title: '首页' },
      ...pathSegments.map((segment, index) => ({
        href: `/${pathSegments.slice(0, index + 1).join('/')}`,
        title: segment.charAt(0).toUpperCase() + segment.slice(1),
      })),
    ];
  };

  const breadcrumbItems = generateBreadcrumbItems();

  const getSelectedKeys = (pathname: string) => {
    const path = pathname.split('/')[1];
    switch (path) {
      case 'dashboard':
        return ['home'];
      case 'article-management':
        return ['articleManagement'];
      case 'attendance':
        return ['clockIn'];
      case 'leave-request':
        return ['leaveRequest'];
      case 'announcement-management':
        return ['announcementManagement'];
      case 'admin-info':
        return ['userManagement', 'adminInfo'];
      case 'user-info':
        return ['userManagement', 'empInfo'];
      case 'employee-password':
        return ['userManagement', 'empPwdManagement'];
      case 'department-management':
        return ['hrManagement', 'departmentManagement'];
      case 'personnel':
        const personnelSubPath = pathname.split('/')[2];
        switch (personnelSubPath) {
          case 'academy':
            return ['hrManagement', 'academyManagement'];
          default:
            return ['hrManagement'];
        }
      case 'attendance-management':
        return ['attendanceManagement'];
      case 'approval':
        const approvalSubPath = pathname.split('/')[2];
        switch (approvalSubPath) {
          case 'leave':
            return ['leaveApproval'];
          default:
            return ['leaveApproval'];
        }
      case 'set-check-in-time':
        return ['setCheckInTime'];
      case 'recruitment':
        const subPath = pathname.split('/')[2];
        switch (subPath) {
          case 'plan':
            return ['recruitmentManagement', 'recruitmentPlan'];
          case 'candidates':
            return ['recruitmentManagement', 'candidateManagement'];
          case 'interviews':
            return ['recruitmentManagement', 'interviewManagement'];
          case 'analytics':
            return ['recruitmentManagement', 'recruitmentAnalytics'];
          case 'offer':
            return ['recruitmentManagement', 'offerManagement'];
          default:
            return ['recruitmentManagement'];
        }
      default:
        return ['home'];
    }
  };

  const renderMenuItem = (item: any) => {
    return (
      <Menu.Item key={item.key} icon={item.icon}>
        <Link href={item.href}>{item.label}</Link>
      </Menu.Item>
    );
  };

  const renderSubMenu = (item: any) => {
    if (item.children) {
      return (
        <Menu.SubMenu key={item.key} icon={item.icon} title={item.label}>
          {item.children.map(renderMenuItem)}
        </Menu.SubMenu>
      );
    }
    return null;
  };

  return (
    <ConfigProvider
      theme={{
        algorithm: theme.defaultAlgorithm,
        token: {
          colorPrimary: '#1890ff',
        },
      }}
    >
      <AntLayout style={{ 
        minHeight: '100vh', 
        background: '#001529',
        margin: 0,
        padding: 0
      }}>
        <Header style={{
          padding: 0,
          margin: 0,
          background: '#001529',
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          zIndex: 1001,
          height: 64,
          lineHeight: '64px',
          borderBottom: '1px solid #303030'
        }}>
          {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
            className: 'trigger',
            onClick: () => setCollapsed(!collapsed),
            style: { color: '#fff', fontSize: '18px', padding: '0 24px', cursor: 'pointer' }
          })}
          <span style={{ marginLeft: '16px', color: '#fff' }}>人力资源管理系统</span>
          <div style={{ 
            float: 'right', 
            marginRight: '16px', 
            position: 'relative',
            height: '100%',  // 确保容器高度与 header 一致
            display: 'flex',
            alignItems: 'center'  // 垂直居中
          }}>
            <Box 
              onClick={handleClick}
              sx={{ 
                position: 'relative',
                width: 44,
                height: 44,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                cursor: 'pointer',
                transition: 'transform 0.3s ease',
                transform: open ? 'scale(1.3)' : 'scale(1)',
                '&:hover': {
                  transform: open ? 'scale(1.3)' : 'scale(1.3)'  // 无论是否打开，悬浮都放大1.3
                }
              }}
            >
              {/* 蓝色空心圆 */}
              <Box sx={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                height: '100%',
                borderRadius: '50%',
                border: '2px solid #1890ff',
                opacity: 0.8,
              }} />
              
              <Avatar
                style={{
                  backgroundColor: '#0050b3',
                  width: 36,
                  height: 36,
                  position: 'relative',
                  zIndex: 1,
                }}
              >
                {userInfo.username?.[0]?.toUpperCase() || 'U'}
              </Avatar>
            </Box>

            <Popper
              open={open}
              anchorEl={anchorEl}
              placement="bottom-end"
              transition
              disablePortal
              modifiers={[  // 添加 modifiers 来防止位置抖动
                {
                  name: 'offset',
                  options: {
                    offset: [0, 4],  // 水平和垂直偏移
                  },
                },
                {
                  name: 'preventOverflow',
                  options: {
                    padding: 8,  // 与视口边缘的距离
                  },
                }
              ]}
              sx={{ 
                zIndex: 1002,
                marginTop: '0 !important'
              }}
            >
              {({ TransitionProps }) => (
                <Grow
                  {...TransitionProps}
                  style={{ transformOrigin: 'top right' }}
                >
                  <Box>
                    <ClickAwayListener onClickAway={handleClose}>
                      <Paper 
                        elevation={8}
                        sx={{
                          minWidth: 280,
                          borderRadius: '16px',
                          overflow: 'hidden',
                          background: 'rgba(255, 255, 255, 0.95)',
                          backdropFilter: 'blur(10px)',
                          border: '1px solid rgba(255, 255, 255, 0.2)',
                          boxShadow: '0 10px 30px rgba(0,0,0,0.2)'
                        }}
                      >
                        <Box sx={{ 
                          p: 3, 
                          background: 'linear-gradient(135deg, #1890ff 0%, #0050b3 100%)',
                          position: 'relative',
                          overflow: 'hidden'
                        }}>
                          {/* 装饰性圆圈 */}
                          <Box sx={{
                            position: 'absolute',
                            top: -20,
                            right: -20,
                            width: 100,
                            height: 100,
                            borderRadius: '50%',
                            background: 'rgba(255, 255, 255, 0.1)',
                          }} />
                          <Box sx={{
                            position: 'absolute',
                            bottom: -30,
                            left: -30,
                            width: 80,
                            height: 80,
                            borderRadius: '50%',
                            background: 'rgba(255, 255, 255, 0.05)',
                          }} />
                          
                          <Box sx={{ 
                            display: 'flex',
                            alignItems: 'center',
                            gap: 2,
                            position: 'relative',
                            zIndex: 1
                          }}>
                            <Avatar
                              style={{
                                width: 36,
                                height: 36,
                                backgroundColor: '#0050b3',
                                color: '#ffffff',
                                fontSize: '16px',
                                fontWeight: 'bold',
                                boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)'
                              }}
                            >
                              {userInfo.username?.[0]?.toUpperCase() || 'U'}
                            </Avatar>
                            <Box>
                              <Typography sx={{ 
                                color: 'white',
                                fontSize: '1.25rem',
                                fontWeight: 'bold',
                                mb: 0.5,
                                textShadow: '0 2px 4px rgba(0,0,0,0.2)'
                              }}>
                                {userInfo.username || '用户'}
                              </Typography>
                              <Typography sx={{ 
                                color: 'rgba(255,255,255,0.85)',
                                fontSize: '0.875rem',
                                display: 'flex',
                                alignItems: 'center',
                                gap: 0.5
                              }}>
                                <PersonIcon sx={{ fontSize: '0.875rem' }} />
                                {userInfo.position || '职位'}
                              </Typography>
                            </Box>
                          </Box>
                        </Box>

                        <MenuList>
                          <MenuItem 
                            onClick={() => {
                              router.push('/profile');
                              handleClose();
                            }}
                            sx={{
                              py: 1.5,
                              px: 3,
                              '&:hover': {
                                background: 'rgba(24,144,255,0.1)',
                              }
                            }}
                          >
                            <ListItemIcon>
                              <PersonIcon sx={{ color: '#1890ff' }} />
                            </ListItemIcon>
                            <ListItemText 
                              primary="个人信息" 
                              primaryTypographyProps={{
                                sx: { fontWeight: 500 }
                              }}
                            />
                          </MenuItem>

                          <MenuItem 
                            onClick={() => {
                              router.push('/change-password');
                              handleClose();
                            }}
                            sx={{
                              py: 1.5,
                              px: 3,
                              '&:hover': {
                                background: 'rgba(24,144,255,0.1)',
                              }
                            }}
                          >
                            <ListItemIcon>
                              <LockIcon sx={{ color: '#1890ff' }} />
                            </ListItemIcon>
                            <ListItemText 
                              primary="修改密码"
                              primaryTypographyProps={{
                                sx: { fontWeight: 500 }
                              }}
                            />
                          </MenuItem>

                          <Divider sx={{ my: 1 }} />

                          <MenuItem 
                            onClick={handleLogout} 
                            sx={{
                              py: 1.5,
                              px: 3,
                              color: '#ff4d4f',
                              '&:hover': {
                                background: 'rgba(255,77,79,0.1)',
                              }
                            }}
                          >
                            <ListItemIcon>
                              <LogoutIcon sx={{ color: '#ff4d4f' }} />
                            </ListItemIcon>
                            <ListItemText 
                              primary="退出登录"
                              primaryTypographyProps={{
                                sx: { fontWeight: 500 }
                              }}
                            />
                          </MenuItem>
                        </MenuList>
                      </Paper>
                    </ClickAwayListener>
                  </Box>
                </Grow>
              )}
            </Popper>
          </div>
        </Header>
        <Sider 
          trigger={null} 
          collapsible 
          collapsed={collapsed}
          style={{
            height: 'calc(100vh - 64px)',
            position: 'fixed',
            left: 0,
            top: 64,
            zIndex: 1000,
            margin: 0,
            padding: 0,
            width: collapsed ? 80 : 200,
            transition: 'all 0.2s',
            overflowY: 'auto',
            overflowX: 'hidden'
          }}
        >
          <div className="logo" />
          <Menu
            theme="dark"
            mode="inline"
            selectedKeys={getSelectedKeys(pathname)}
            defaultOpenKeys={['userManagement', 'hrManagement', 'recruitmentManagement']}
            className={`${menuStyles} scrollable-menu`}
            style={{
              border: 'none',
              margin: 0,
              padding: 0
            }}
          >
            {sideMenuItems.map((item) => 
              item.children ? renderSubMenu(item) : renderMenuItem(item)
            )}
          </Menu>
        </Sider>
        <AntLayout style={{ 
          marginLeft: collapsed ? 80 : 200,
          background: '#f0f2f5',
          minHeight: '100vh',
          padding: 0,
          marginTop: 64,
          transition: 'margin-left 0.2s'
        }}>
          <Content style={{
            padding: '24px 16px',
            minHeight: 'calc(100vh - 64px)',
            background: '#f0f2f5',
            position: 'relative'
          }}>
            <ContentArea>
              {children}
            </ContentArea>
          </Content>
        </AntLayout>
      </AntLayout>
    </ConfigProvider>
  );
};

// 最简单的方式
export default dynamic(() => Promise.resolve(AppLayout), {
  ssr: false,
  loading: () => <LoadingLayout />
});